package com.ruoyi.web.controller.business;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.IIndicatorService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Indicator;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用于存储评价指标及其详细信息Controller
 *
 * @author song
 * @date 2024-11-24
 */
@Api(tags = "评价指标管理")
@RestController
@RequestMapping("/business/indicator")
public class IndicatorController extends BaseController
{
    @Autowired
    private IIndicatorService indicatorService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询用于存储评价指标及其详细信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:indicator:list')")
    @ApiOperation(value = "查询评价指标列表")
    @GetMapping("/list")
    public TableDataInfo list(Indicator indicator)
    {
        startPage();

        List<Indicator> list = indicatorService.selectIndicatorList(indicator);
        return getDataTable(list);
    }

    /**
     * 导出用于存储评价指标及其详细信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:indicator:export')")
    @Log(title = "用于存储评价指标及其详细信息", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "导出评价指标列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Indicator indicator)
    {
        List<Indicator> list = indicatorService.selectIndicatorList(indicator);
        ExcelUtil<Indicator> util = new ExcelUtil<Indicator>(Indicator.class);
        util.exportExcel(response, list, "用于存储评价指标及其详细信息数据");
    }

    /**
     * 获取用于存储评价指标及其详细信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:indicator:query')")
    @ApiOperation(value = "获取评价指标详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(indicatorService.selectIndicatorById(id));
    }

    /**
     * 新增用于存储评价指标及其详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:indicator:add')")
    @Log(title = "积分规则1", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增评价指标")
    @PostMapping
    public AjaxResult add(@RequestBody Indicator indicator)
    {
        //判断指标是否存在
        if (indicatorService.checkIndicatorNameUnique(indicator))
        {
            return error("指标已存在");
        }

        //判断所有权重不能大于100
        int sumWeight = indicatorService.getAllWeight(indicator);
        if(sumWeight+Integer.parseInt(indicator.getWeight().toString())>100){
            return warn("权重不能大于100");
        }

        return toAjax(indicatorService.insertIndicator(indicator));
    }

    /**
     * 修改用于存储评价指标及其详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:indicator:edit')")
    @Log(title = "积分规则1", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改评价指标")
    @PutMapping
    public AjaxResult edit(@RequestBody Indicator indicator)
    {
        //判断指标是否存在
        //判断所有权重不能大于100
        int sumWeight = indicatorService.getAllWeight(indicator);
        Indicator old = indicatorService.selectIndicatorById(indicator.getId());

        sumWeight = sumWeight - new BigDecimal(old.getWeight().toString()).intValue();

        if(sumWeight+Integer.parseInt(indicator.getWeight().toString())>100){
            return warn("权重不能大于100");
        }

        return toAjax(indicatorService.updateIndicator(indicator));
    }

    /**
     * 删除用于存储评价指标及其详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:indicator:remove')")
    @Log(title = "积分规则1", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除评价指标")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(indicatorService.deleteIndicatorByIds(ids));
    }


    @ApiOperation(value = "查询履职能力指标类型列表")
    @GetMapping("/getJobPerformanceType")
    public AjaxResult getJobPerformanceType()
    {
        String dictType = "job_performance_type";
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    @ApiOperation(value = "查询培训意愿指标类型列表")
    @GetMapping("/getImprovementWillType")
    public AjaxResult getImprovementWillType()
    {
        String dictType = "improvement_will_type";
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    @ApiOperation(value = "查询指标对应的模版信息")
    @GetMapping("/getIndicatorTemplateInfoV2/{id}/{indicatorId}")
    public AjaxResult getIndicatorTemplateInfo(@PathVariable("id") Long id,@PathVariable("indicatorId") Long indicatorId) {
        Map<String, Object> result = new HashMap<>();
        SysDictData sysDictData = dictDataService.selectDictDataById(id);
        String weight = sysDictData.getDictValue();
        result.put("weight", weight);

        Indicator indicator = indicatorService.selectIndicatorById(indicatorId);

            if(Objects.equals(indicator.getEvaluationMetric(), "184") || Objects.equals(indicator.getEvaluationMetric(), "185") || Objects.equals(indicator.getEvaluationMetric(), "186") || Objects.equals(indicator.getEvaluationMetric(), "187") || Objects.equals(indicator.getEvaluationMetric(), "188") || Objects.equals(indicator.getEvaluationMetric(), "189")){
            result.put("isEditName", true);
        }else {
            result.put("isEditName", false);
        }

        // 获取类型
        String dictType = sysDictData.getRemark();
        SysDictType sysDictType = dictTypeService.selectDictTypeById(Long.parseLong(dictType));
        result.put("assessmentDetails", sysDictType.getRemark());

        String dataTemplate = sysDictType.getDataTemplate();
        result.put("dataTemplate", dataTemplate);

        // 获取模版数据
        List<SysDictData> datas = dictTypeService.selectDictDataByType(sysDictType.getDictType());

        // 提取 createBy 值
        List<String> createByValues = datas.stream()
                .map(item -> (String) item.getDictValue())
                .collect(Collectors.toList());

        // 创建正则表达式模式
        Pattern pattern = Pattern.compile("\\$\\{(\\d+)\\}");

        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(dataTemplate);

        // 使用 StringBuffer 构建最终的字符串
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            int index = Integer.parseInt(matcher.group(1)) - 1;
            String replacement = index < createByValues.size() ? createByValues.get(index) : matcher.group();
            matcher.appendReplacement(sb, replacement);
        }

        // 完成替换
        matcher.appendTail(sb);

        String scoringCriteria = sb.toString().replaceAll("\\$\\{weight\\}", weight);
        System.out.println(scoringCriteria);
        result.put("scoringCriteria", scoringCriteria);
        result.put("datas", datas);

        return success(result);
    }

    @ApiOperation(value = "查询指标对应的模版信息")
    @GetMapping("/getIndicatorTemplateInfo/{id}")
    public AjaxResult getIndicatorTemplateInfos(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        SysDictData sysDictData = dictDataService.selectDictDataById(id);
        String weight = sysDictData.getDictValue();
        result.put("weight", weight);

        // 获取类型
        String dictType = sysDictData.getRemark();
        SysDictType sysDictType = dictTypeService.selectDictTypeById(Long.parseLong(dictType));
        result.put("assessmentDetails", sysDictType.getRemark());

        String dataTemplate = sysDictType.getDataTemplate();
        result.put("dataTemplate", dataTemplate);

        // 获取模版数据
        List<SysDictData> datas = dictTypeService.selectDictDataByType(sysDictType.getDictType());

        // 提取 createBy 值
        List<String> createByValues = datas.stream()
                .map(item -> (String) item.getDictValue())
                .collect(Collectors.toList());

        // 创建正则表达式模式
        Pattern pattern = Pattern.compile("\\$\\{(\\d+)\\}");

        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(dataTemplate);

        // 使用 StringBuffer 构建最终的字符串
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            int index = Integer.parseInt(matcher.group(1)) - 1;
            String replacement = index < createByValues.size() ? createByValues.get(index) : matcher.group();
            matcher.appendReplacement(sb, replacement);
        }

        // 完成替换
        matcher.appendTail(sb);

        String scoringCriteria = sb.toString().replaceAll("\\$\\{weight\\}", weight);
        System.out.println(scoringCriteria);
        result.put("scoringCriteria", scoringCriteria);
        result.put("datas", datas);

        return success(result);
    }
}
